<script setup lang="ts">
import { ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'vue3-dnd';

import { uploadImg } from '#/api';

import { shuffleArray } from '../../tools';
import MoveItem from './imgMove/moveItem.vue';

const formState: any = defineModel();

const imageList = ref(initImageRef());
function initImageRef() {
  return (
    formState.value.descPicList.map((item: any, index: number) => {
      return {
        url: item,
        id: index + 1,
        islodin: false,
      };
    }) || []
  );
}
const moveCard = (dragIndex: number, hoverIndex: number) => {
  const item = imageList.value[dragIndex];
  imageList.value.splice(dragIndex, 1);
  imageList.value.splice(hoverIndex, 0, item);
  // resetImageId();
};
function removeCard(index: number) {
  imageList.value.splice(index, 1);
  resetImageId();
}
function resetImageId() {
  imageList.value.forEach((item: any, index: number) => {
    item.id = index + 1;
  });
  formState.value.descPicList = imageList.value.map((item: any) => item.url);
}

function upimagefunc() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  // 支持多张
  input.multiple = true;
  input.addEventListener('change', (e: any) => {
    const files = e.target.files;
    for (const file of files) {
      // 限制最大5m
      if (file.size > 5 * 1024 * 1024) {
        return message.error('文件大小不能超过5M');
      }
      const img = new Image();
      img.src = URL.createObjectURL(file);
      img.addEventListener('load', () => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.addEventListener('load', (e: any) => {
          const addItem = {
            url: e.target.result,
            id: imageList.value.length + 1,
            islodin: true,
          };
          imageList.value.push(addItem);
          const formDatas = new FormData();
          formDatas.append('files', file);
          formDatas.append('shopId', formState.value.shopId);
          formDatas.append('offerId', formState.value.offerId);
          uploadImg(formDatas).then((res) => {
            addItem.url = res[0] || addItem.url;
            addItem.islodin = false;
            // const getDater = imageList.value.find(
            //   (item: any) => item.id === addItem.id,
            // );
            // getDater.islodin = false;
            // getDater.url = res[0] || getDater.url;
            resetImageId();
          });
        });
      });
    }
  });
  input.click();
}

function deletAllImage() {
  formState.value.descPicList = [];
  imageList.value = initImageRef();
  // resetImageId();
}
function shuffleArrayImage() {
  imageList.value = shuffleArray(imageList.value);
  resetImageId();
}
const splitNum = ref(5);

function splitImage() {}
watch(formState, () => {
  imageList.value = initImageRef();
});
</script>

<template>
  <div class="flex">
    <div class="mr-2 w-60 overflow-hidden rounded-sm border">
      <div class="bg-gray-200 px-2">页面预览</div>
      <div class="w-full overflow-y-scroll bg-gray-100" style="height: 700px">
        <img
          v-for="(item, index) in formState.descPicList"
          :key="index"
          :src="item"
          alt=""
        />
      </div>
    </div>
    <div class="flex-1 overflow-hidden rounded-sm border p-4">
      <div class="flex items-center justify-between">
        <div>
          <div class="text-base font-semibold">详情编辑</div>
          <div class="text-xs font-medium">
            已上传{{
              formState.descPicList.length
            }}/50张，拖拽可调整顺序，单张详情图宽高比不超5000*20000px，大小5M内，仅支持jpg/jpeg/png格式
          </div>
        </div>
        <a-button type="primary" @click="upimagefunc">上传图片</a-button>
      </div>
      <div class="mt-4 overflow-y-scroll" style="height: 530px">
        <DndProvider :backend="HTML5Backend">
          <div class="flex flex-wrap">
            <div
              v-for="(item, index) in imageList"
              :key="item.id"
              class="mb-2 mr-2"
            >
              <MoveItem
                :id="item.id"
                :end="resetImageId"
                :index="index"
                :islodin="item.islodin"
                :move-card="moveCard"
                :remove-card="removeCard"
                :url="item.url"
                class-name="w-20 h-20"
              />
            </div>
          </div>
        </DndProvider>
      </div>
      <a-divider />
      <div class="mt-4">
        <a-space class="w-full justify-end">
          <a-button v-if="0" type="primary"> 添加文字 </a-button>
          <a-button type="primary" @click="deletAllImage">
            删除全部图片
          </a-button>
          <a-button type="primary" @click="shuffleArrayImage">
            打乱详情图
          </a-button>
          <a-popover v-if="0" title="输入分割份数">
            <template #content>
              <a-space>
                <a-input-number
                  v-model:value="splitNum"
                  :formatter="(value: any) => `${value}份`"
                  :max="50"
                  :min="1"
                  :parser="(value: any) => value.replace('份', '')"
                  :precision="0"
                  :step="1"
                  class="w-40"
                />
                <a-button type="primary" @click="splitImage"> 确认</a-button>
              </a-space>
            </template>
            <a-button type="primary" @click="shuffleArrayImage">
              重新分割
            </a-button>
          </a-popover>
        </a-space>
      </div>
    </div>
  </div>
</template>
